package com.scidpro.twic;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Environment;

import com.scidpro.IDownloadCallback;
import com.scidpro.MyBooksListActivity;
import com.scidpro.R;
import com.scidpro.ScidAndroidActivity;
import com.scidpro.Tools;

public class ImportZipTask extends AsyncTask {

	private Context context;
	private IDownloadCallback downloadCallback;
	private ProgressDialog progressDlg;
	private String url;

	@Override
	protected Object doInBackground(Object... params) {
		File result = null;
		this.context = (Context) params[0];
		this.downloadCallback = (IDownloadCallback) params[1];
		this.progressDlg = (ProgressDialog) params[2];
		this.url = (String) params[3];

		sendNotification("Downloading book");

		TwicDownloader downloader = new TwicDownloader();
		try {
			result = downloader.getPgnFromZipUrl(Environment.getExternalStorageDirectory() + File.separator + ScidAndroidActivity.SCID_DIRECTORY, url);
		} catch (IOException e) {
			if (context != null && context instanceof Activity) {
				Tools.showErrorMessage((Activity) context, context.getText(R.string.download_error) + " (" + e.getMessage() + ")");
			}
		}
		return result;
	}

	@Override
	protected void onPostExecute(Object result) {
		if (progressDlg != null) {
			progressDlg.dismiss();
		}
		if (downloadCallback != null) {
			if (result != null) {
				downloadCallback.downloadSuccess((File) result);

				Tools.importPgnFile((Activity) context, (File) result, 0);
			} else {
				downloadCallback.downloadFailure(this.url);
			}
		}
		if (result != null) {
			sendNotification("Download complete");
		} else {
			sendNotification("Download failure");
		}
	}

	private void sendNotification(CharSequence tickerText) {
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);

		int icon = android.R.drawable.ic_notification_overlay;
		long when = System.currentTimeMillis();

		Notification notification = new Notification(icon, tickerText, when);

		CharSequence contentTitle = "Downloading book";
		CharSequence contentText = tickerText;
		Intent notificationIntent = new Intent(context.getApplicationContext(), MyBooksListActivity.class);
		PendingIntent contentIntent = PendingIntent.getActivity(context.getApplicationContext(), 0, notificationIntent, 0);

		notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

		int HELLO_ID = 1;

		mNotificationManager.notify(HELLO_ID, notification);
	}

}
